<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>table 组件综合演示 - Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="layui/css/layui.css" rel="stylesheet">
</head>
<body>

<!--添加的表单-->
<form class="layui-form" action=""  style="display: none; padding: 15px;"  id="addForm">
    <div class="layui-form-item">
        <label class="layui-form-label">桌型</label>
        <div class="layui-input-block">
            <input type="text" name="dname" required  lay-verify="required" placeholder="请输入桌型" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-block">
            <input type="text" name="img" required  lay-verify="required" placeholder="请选择图片" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--修改的表单 -->
<form class="layui-form" action=""  style="display: none; padding: 15px;"  id="updateForm" lay-filter="updateForm">
    <div class="layui-form-item">
        <label class="layui-form-label">id</label>
        <div class="layui-input-block">
            <input type="text" name="id" readonly required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">桌型</label>
        <div class="layui-input-block">
            <input type="text" name="dname" required  lay-verify="required" placeholder="请输入桌型" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-block">
            <input type="text" name="img" required  lay-verify="required" placeholder="请选择图片" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo2">立即修改</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!-- 表格容器-->
<div style="padding: 16px;">
    <table class="layui-hide" id="test" lay-filter="test"></table>
</div>

<!--头部工具条 -->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
    </div>
</script>

<!--行内工具条 -->
<script type="text/html" id="toolDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs layui-bg-red" lay-event="del">删除</a>

    </div>
</script>


<script src="layui/layui.js"></script>
<script>
    layui.use(['table', 'dropdown'], function(){
        var table = layui.table;
        var dropdown = layui.dropdown;
        var $ = layui.$;
        var form = layui.form;

        //监听表单提交
        form.on('submit(formDemo)', function(data){
            // 向服务端发送请求
            $.ajax({
                url:'/desk/',
                type:'post',
                data:JSON.stringify(data.field),
                contentType:'application/json',
                dataType:'json',
                success:function(res){
                    layer.closeAll();  //消除所有弹窗
                    table.reload("test",{});  //刷新表格
                }
            })
            return false;
        });

        //监听提交----修改
        form.on('submit(formDemo2)', function(data){
            // 向服务端发送请求
            $.ajax({
                url:'/desk/',
                type:'put',
                data:JSON.stringify(data.field),
                contentType:'application/json',
                dataType:'json',
                success:function(res){
                    layer.closeAll();
                    table.reload("test",{});
                    layer.msg('修改成功', {icon:1})
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                    layer.msg('修改失败', {icon: 2});
                }
            })
            return false;
        });

        // 创建渲染实例
        table.render({
            elem: '#test',
            url: '/desk/',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips',
                onClick: function(obj) { // 2.9.12+
                    layer.alert('自定义工具栏图标按钮');
                }
            }],
            height: 'full-35', // 最大高度减去其他容器已占有的高度差
            css: [ // 重设当前表格样式
                '.layui-table-tool-temp{padding-right: 145px;}'
            ].join(''),
            cellMinWidth: 80,
            totalRow: true, // 分页
            page: true,
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field:'id', fixed: 'left', width:80, title: 'ID', sort: true, totalRow: '合计：'},
                {field:'dname', width:80, title: '桌型'},
                {field:'img', width:80, title: '图片'},
                {fixed: 'right', title:'操作', width: 134, minWidth: 125, templet: '#toolDemo'}
            ]],
            error: function(res, msg){
                console.log(res, msg)
            }
        });

        // 工具栏事件
        table.on('toolbar(test)', function(obj){
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch(obj.event){
                case 'add':
                    layer.open({
                        title:'添加',
                        type:1,
                        area:['80%,80%'],
                        content:$("#addForm")
                    });
                    break;
                case 'del':
                    var getData = table.getData(id);
                    console.log(getData);
                    layer.alert(layui.util.escape(JSON.stringify(getData)));
                    break;
            };
        });


        // 表头自定义元素工具事件 --- 2.8.8+
        table.on('colTool(test)', function(obj){
            var event = obj.event;
            console.log(obj);
            if(event === 'email-tips'){
                layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
                    title: '当前列属性配置项'
                });
            }
        });

        // 触发单元格工具事件
        table.on('tool(test)', function(obj){ // 双击 toolDouble
            var data = obj.data; // 获得当前行数据
            // console.log(obj)
            if(obj.event === 'edit'){
                //设置表单的数据显示（回显）
                form.val("updateForm",data)
                //弹窗
                layer.open({
                    title: '编辑 - id:'+ data.id,
                    type: 1,
                    area: ['80%','80%'],
                    content: $("#updateForm")
                });
            }
            else if(obj.event === 'del'){
                layer.confirm('确定删除行 [id: '+ data.id +'] 吗', function(index) {
                    obj.del(); // 删除对应行（tr）的DOM结构
                    layer.close(index);
                    // 向服务端发送删除指令
                    $.ajax({
                        url:'/desk/'+data.id,
                        type:'DELETE',
                        dataType:'json',
                        success: function(res){
                            console.log(res)
                            layer.msg('删除成功', {icon:1})
                        },
                        error: function(xhr, status, error) {
                            console.error('Error:', error);
                            layer.msg('删除失败', {icon: 2});
                        }
                    })
                });
            }
        });


        // table 滚动时移除内部弹出的元素
        var tableInst = table.getOptions('test');
        tableInst.elem.next().find('.layui-table-main').on('scroll', function() {
            dropdown.close('dropdown-table-tool');
        });

        // 触发表格复选框选择
        table.on('checkbox(test)', function(obj){
            console.log(obj)
        });

        // 触发表格单选框选择
        table.on('radio(test)', function(obj){
            console.log(obj)
        });

        // 行单击事件
        table.on('row(test)', function(obj){
            //console.log(obj);
            //layer.closeAll('tips');
        });
        // 行双击事件
        table.on('rowDouble(test)', function(obj){
            console.log(obj);
        });

        // 单元格编辑事件
        table.on('edit(test)', function(obj){
            var field = obj.field; // 得到字段
            var value = obj.value; // 得到修改后的值
            var data = obj.data; // 得到所在行所有键值
            // 值的校验
            if(field === 'email'){
                if(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(obj.value)){
                    layer.tips('输入的邮箱格式不正确，请重新编辑', this, {tips: 1});
                    return obj.reedit(); // 重新编辑 -- v2.8.0 新增
                }
            }
            // 编辑后续操作，如提交更新请求，以完成真实的数据更新
            // …
            layer.msg('编辑成功', {icon: 1});

            // 其他更新操作
            var update = {};
            update[field] = value;
            obj.update(update);
        });
    });
</script>
</body>
</html>